<template>
  <el-container class="dashboard-container">
    <!-- 侧边栏 -->
    <el-aside width="180px" class="sidebar">
      <el-menu default-active="1" class="menu">
        <!-- 退出登录 -->
        <el-menu-item index="1" @click="goHome">
          <el-icon><HomeFilled /></el-icon>
          <span>退出登录</span>
        </el-menu-item>

        <!-- 组队详情 -->
        <el-menu-item index="6" @click.native="checkIdentity">
          <el-icon><UserFilled /></el-icon>
          <span>组队详情</span>
        </el-menu-item>

        <!-- 分工智能助手 -->
        <el-menu-item index="5" @click="goToReferenceQuestionnaire">
          <el-icon><CopyDocument /></el-icon>
          <span>分工智能助手</span>
        </el-menu-item>

        <!-- 查看任务安排 -->
        <el-menu-item index="2" @click="goTasks">
          <el-icon><Document /></el-icon>
          <span>任务安排</span>
        </el-menu-item>

        <!-- 查看小组成员 -->
        <el-menu-item index="3" @click="goMembers">
          <el-icon><User /></el-icon>
          <span>推进情况</span>
        </el-menu-item>

        <!-- 讨论 -->
        <el-menu-item index="7" @click="goDiscussion">
          <el-icon><Message /></el-icon>
          <span>讨论</span>
        </el-menu-item>

        <!-- 小组评分 -->
        <el-menu-item index="8" @click="goScoring">
          <el-icon><EditPen /></el-icon>
          <span>小组评分</span>
        </el-menu-item>

        <!-- 设置 -->
        <el-menu-item index="4" @click="goSettings">
          <el-icon><Setting /></el-icon>
          <span>设置</span>
        </el-menu-item>

        <!-- 举报 -->
        <el-menu-item index="9" @click="goReport">
          <el-icon><BellFilled /></el-icon>
          <span>举报</span>
        </el-menu-item>
      </el-menu>
    </el-aside>


    <el-container class="main-content">

      <el-main>


        <el-row :gutter="20">
  <el-col :span="24">
    <el-card class="task-table">
      <h3 style="font-weight: bold;">当前小组个人任务</h3>
      <!-- 当 subtasks 数组存在且非空时，展示表格；否则显示“暂无任务分配” -->
      <el-table :data="subtasks" stripe v-if="subtasks && subtasks.length">
        <!-- 子任务描述 -->
        <el-table-column
          prop="description"
          label="子任务描述"
          width="200"
        ></el-table-column>

        <!-- 负责人 -->
        <el-table-column
          prop="assigned_to"
          label="子任务负责人"
          width="150"
        ></el-table-column>

        <!-- 完成期限（对应 end_date） -->
        <el-table-column
          prop="end_date"
          label="完成期限"
          width="120"
        ></el-table-column>

        <!-- 任务状态 -->
        <el-table-column prop="status" label="任务状态">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'on_time'
                ? 'success'
                : row.status === 'late'
                ? 'danger'
                : 'info'"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div v-else>
        <p>暂无任务分配</p>
      </div>
    </el-card>
  </el-col>
</el-row>

        <!-- Task Detail -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card class="task-table">
              <h3 style="font-weight: bold;">任务描述</h3>
              <!-- 在数据加载完之前先做判定，避免读取 undefined -->
              <div v-if="taskDetailData.task && taskDetailData.task.title">
                <p><strong>任务名称:</strong> {{ taskDetailData.task.title }}</p>
                <p><strong>描述:</strong> {{ taskDetailData.task.description }}</p>
                <p><strong>截止日期:</strong> {{ taskDetailData.task.deadline }}</p>
                <p><strong>评分标准:</strong> {{ taskDetailData.task.scoring_criteria }}</p>
                <p><strong>状态:</strong> {{ taskDetailData.task.status }}</p>
              </div>
              <div v-else>
                <p>Loading or no data...</p>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- User Info -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card class="dashboard-card">
              <h3 style="font-weight: bold;">用户信息</h3>
              <div v-if="taskDetailData.user && taskDetailData.user.username">
                <p><strong>用户名:</strong> {{ taskDetailData.user.username }}</p>
                <p><strong>邮箱:</strong> {{ taskDetailData.user.email }}</p>
              </div>
              <div v-else>
                <p>Loading user data...</p>
              </div>
              <!-- 展示用户所在的小组信息 -->
              <div v-if="groupInfo && groupInfo.group_id">
                <p><strong>所在小组ID:</strong> {{ groupInfo.group_id }}</p>
                <p><strong>本组组长:</strong> {{ groupInfo.group_name }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>

      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { defineComponent, ref, onMounted } from "vue";
import * as echarts from "echarts";
import { Document, Menu, User, Setting, HomeFilled, CopyDocument, UserFilled, Message, EditPen, BellFilled } from "@element-plus/icons-vue";
import { useRouter } from 'vue-router';
import axios from '@/axiosInstance';
import router from "@/router/index.js";  // 如果你已经在其他地方配置了 axios 实例，确保正确导入

export default defineComponent({
  name: "LeaderDashboard",
  components: { Menu, HomeFilled, User, Setting, Document, CopyDocument, UserFilled, Message, EditPen, BellFilled},
  setup() {
    const taskId = ref(null);
    const sysUserId = ref(null);
    const tasks = ref([]);
    const chartRef = ref(null);
    const user = ref({});
    const taskDetailData = ref({});
    // 存储子任务列表（如果有需要显示）
    const subtasks = ref([]);
    // 存储用户所在的小组信息
    const groupInfo = ref({});

    // 获取任务ID和用户ID
    onMounted(async () => {  // Marking onMounted as async to use await inside it
      taskId.value = new URLSearchParams(window.location.search).get('taskId');
      sysUserId.value = new URLSearchParams(window.location.search).get('sysUserId');
      console.log('获取的任务ID:', taskId.value);
      console.log('获取的用户ID:', sysUserId.value);

  // Ensuring the functions are called in sequence
      await fetchTaskDetails();
      await fetchUserGroup();
      await fetchSubtasksByGroup();  // This will now run after the group info is fetched
    });

    const fetchTaskDetails = async () => {
      try {
        const response = await axios.get(`http://39.105.217.183:8000/api/show_task_detail/${taskId.value}/`, {
          params: { user_id: sysUserId.value }
        });
        //console.log('响应数据:', response.data);
        console.log('响应数据:', response);
        //console.log("任务详情:", tasks.value[0].title);  // 访问任务标题
        //console.log("用户详情:", user.value[0].username);  // 访问用户名
    // 假设返回的数据格式为 { task: {...}, user: {...} }
      if (response.data) {
        taskDetailData.value = response.data;
        console.log('传递:', taskDetailData);
        console.log(taskDetailData.value.task.title);
      } else {
        console.error("未能获取任务详情");
      }
    } catch (error) {
      console.error("获取任务详情失败:", error.message || error);
   }
  };

  // 获取用户所在小组的信息（后端接口返回 {group_id, group_name, ...}）
    const fetchUserGroup = async () => {
       console.log("尝试获取小组信息");
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/user/getgroupbytask/", {
          params: { user_id: sysUserId.value, task_id: taskId.value }
        });
        console.log("组信息响应数据:", response.data);
        if (response.data && response.data.group_id) {
          groupInfo.value = response.data;
          console.log("小组信息:", groupInfo.value);
        } else {
          console.log("该用户尚未加入小组");
        }
      } catch (error) {
        console.error("获取小组信息失败:", error.message || error);
      }
    };

    // 获取小组信息并传递给子任务请求
    const fetchSubtasksByGroup = async () => {
  try {
    if (!groupInfo.value || !groupInfo.value.group_id) {
      console.error("groupId 未定义");
      return;
    }
    const response = await axios.get(`http://39.105.217.183:8000/api/subtasks/group/${groupInfo.value.group_id}/`);
    console.log("子任务响应数据:", response.data);

    if (Array.isArray(response.data)) {
      // Transform the data into a more readable format
      subtasks.value = response.data.map(subtask => {
        return {
          id: subtask.id,
          description: subtask.description,
          assigned_to: subtask.assigned_to,  // Assuming `assigned_to` has a `username` property
          end_date: subtask.end_date,
          status: subtask.status,  // Make sure this matches your actual status field
        };
      });
    } else {
      console.error("返回的子任务数据格式不对", response.data);
    }
  } catch (error) {
    console.error("获取子任务失败:", error.message || error);
  }
};

    const initChart = () => {
      const chart = echarts.init(chartRef.value);
      chart.setOption({
        series: [
          {
            type: "pie",
            radius: ["50%", "70%"],
            label: { show: false },
            data: [
              { value: 50, name: "Completed", itemStyle: { color: "#34ebba" } },
              { value: 30, name: "In Progress", itemStyle: { color: "#e3eb34" } },
              { value: 20, name: "To Do", itemStyle: { color: "#eb4034" } },
            ],
          },
        ],
      });
    };

    const goToReferenceQuestionnaire = () => {
      // 将 taskId 一起传递到参考问卷页面
      router.push({ path: '/reference-questionnaire', query: {
          taskId: taskId.value,
          groupId: groupInfo.value.group_id,
          UserId: sysUserId.value,
          UserName: taskDetailData.value.user.username,
      } });
    };

    const fetchTaskLeaders = async (taskId, userId) => {
      try {
        const response = await axios.get(`/tasks/${taskId}/leaders/`);
        if (response.data.status === 'success') {
          const leaders = response.data.data;
          console.log('组长名单:', leaders);
          console.log('当前用户的ID:', userId);
          console.log('当前任务的ID:', taskId);
          const isLeader = leaders.some(leader => leader.user_id === Number(userId));
          if (isLeader) {
            console.log('是组长');
            router.push({ path: '/team-application', query: {
              taskId: taskId,
              groupId: groupInfo.value.group_id, // 传递小组ID
              UserId: sysUserId.value,
              UserName: taskDetailData.value.user.username, // 传递用户名
            } });
          } else {
            console.log('是组员');
            router.push({ path: '/select-leader', query: {
              taskId: taskId,
              groupId: groupInfo.value.group_id,
              UserId: sysUserId.value,
              UserName: taskDetailData.value.user.username, // 传递用户名
            } });
          }
        } else {
          console.error('获取组长名单失败:', response.data.message);
        }
      } catch (error) {
        console.error('获取组长信息失败:', error);
      }
    };

    const checkIdentity = () => {
      fetchTaskLeaders(taskId.value, sysUserId.value);
    };

    const goHome = () => {
      router.push({
        path: '/',
        query: { taskId: taskId.value }
      });
    };

    const goTasks = () => {
      router.push({
        path: '/tasks',
        query: { taskId: taskId.value, groupId: groupInfo.value.group_id, sysUserId: sysUserId.value }
      });
    };

    const goMembers = () => {
  router.push({
    path: "/members",
    query: {
      taskId: taskId.value,
      groupId: groupInfo.value.group_id, // 传递小组ID
      sysUserId: sysUserId.value,
      sysUserName: taskDetailData.value.user.username, // 传递用户名
    }
  });
};

    const goSettings = () => {
      router.push({
        path: '/settings',
        query: { taskId: taskId.value }
      });
    };

    const goDiscussion = () => {
      router.push({
        path: '/discussion',
        query: { taskId: taskId.value, groupId: groupInfo.value.group_id, sysUserId: sysUserId.value }
      });
    };

    const goScoring = () => {
      router.push({
        path: '/student-scoring',
        query: {
          taskId: taskId.value,
          groupId: groupInfo.value.group_id, // 传递小组ID
          sysUserId: sysUserId.value,
          sysUserName: taskDetailData.value.user.username, // 传递用户名
        }
      });
    };

    const goReport = () => {
      router.push({
        path: '/report',
        query: { taskId: taskId.value }
      });
    };



    return {
      user,
      tasks,
      chartRef,
      fetchTaskDetails,
      initChart,
      goToReferenceQuestionnaire,
      taskDetailData,
      checkIdentity,
      goHome,
      goTasks,
      goMembers,
      goSettings,
      goDiscussion,
      goScoring,
      goReport,
      groupInfo,
      fetchSubtasksByGroup,
      subtasks,
    };
  },
});
</script>

<style>
/* 确保背景能够全局生效 */
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden; /* 防止水平滚动条 */
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  display: flex;
}

/* 修复 dashboard-container 遮挡背景 & 过窄问题 */
.dashboard-container {
  display: flex;
  width: 100%;
  max-width: 1240px;
  min-width: 100vw;
  margin: 0;
  padding: 0;
  background: transparent; /* 透明，不盖住 body 背景 */
}

/* 侧边栏 */
.sidebar {
  width: 180px;
  background: #f8f9fa;
  height: 100vh;
  padding-top: 20px;
  border-right: 1px solid #ddd;
  flex-shrink: 0; /* 防止 sidebar 变形 */
}

/* 主内容区域 */
.main-content {
  flex: 1;
  padding: 30px;
  background-color: rgba(255, 255, 255, 0.9); /* 90% 透明 */
}

/* 任务表格 */
.task-table {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

/* 统计图表 */
.chart-container {
  width: 100%;
  height: 200px;
}
</style>